package com.ljw.http.client;

import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liujw
 * @create 2020/10/12 14:48
 */
public class JavaUrlConnectionClient {

    static {
        try {
            HttpsURLConnection.setDefaultSSLSocketFactory(SslUtil.buildSSLContext().getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier((urlHostName, session) -> true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String sendHttpURLConnection(String urlPath, Map<String, String> headers, String paramBody, String method) throws IOException {
        String result;
        URL url = new URL(urlPath);
        URLConnection urlConnection = url.openConnection();
        if (urlConnection instanceof HttpURLConnection) {
            HttpURLConnection connection = (HttpURLConnection) urlConnection;
            //设置参数
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod(method);
            // 请求头属性
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Connection", "Keep-alive");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Accept", "application/json");
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    String value = entry.getValue();
                    if (StringUtils.isBlank(value)) {
                        continue;
                    }
                    connection.setRequestProperty(entry.getKey(), value);
                }
            }
            // 连接超时时间
            connection.setConnectTimeout(300);
            // 写入入参
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(paramBody.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            outputStream.close();

            // 读取返回信息
            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                StringBuffer sb = new StringBuffer();
                String readLine;
                BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append(System.lineSeparator());
                }
                responseReader.close();
                result = sb.toString();
            } else if (HttpURLConnection.HTTP_UNAUTHORIZED == connection.getResponseCode()) {
                StringBuffer sb = new StringBuffer();
                String readLine;
                BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append(System.lineSeparator());
                }
                responseReader.close();
                throw new RuntimeException("Failed! responseCode=" + connection.getResponseCode() + " message=" + sb);
            } else {
                throw new RuntimeException("Failed! responseCode=" + connection.getResponseCode());
            }
        } else {
            throw new RuntimeException("Not http request!");
        }
        return result;
    }


    public static void main(String[] args) throws IOException  {
        String urlPath = "https://10.10.20.143:28000/cfgmgr/queryPolicy";

        Map<String, String> headers = new HashMap<>(2);
        headers.put("csrfTokenHoneypot", "1c7cd1dcec5bbf358dfe25a7f99a25dfcf8ef81c3eb19a638bdd5072a7c4c6d5bbd503d27ab310b3b3125b760451efe0f8af363728aeea0dabf83b2b26337a9559adef4fd4a59c2580d934368e8b2b09d904f1cd39e506c2d9fbfba4f265e4efb2bc5b7780cb7787ad1c5ab908b1519f880371b3f7d14b87b0fd7892a305d6d258dc97af6da97fa7466baf29614e69dfd1e8aa218c943676b00632a00497876aad8cc9ec81e97dc995727f61a2f9d6be57959127b115583fa7a94f025fad31609b350316b2d1b482048e501ce9dbbfd41bcd5a02b347b0ddec7fda7fd5f419cfe731b307c87badceb5f3d1add93fcdd6ddc15fdead39a36375d98c87dee8c0a26197c908f0943425298be24e78df35c4");
        headers.put("Cookie", "JSESSIONID=54ECE4C800D0D401DEFAB69EA9973D47");

        String paramBody = "{\"currentPage\":1,\"pageSize\":10}";

        String result = sendHttpURLConnection(urlPath, headers, paramBody, "POST");
        System.out.println(result);
    }
}
